/*
 * Copyright (C) 2016 Mobvoi Inc.
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.umeox.moto.watch.themes.widget;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Space;

import androidx.annotation.IdRes;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.umeox.moto.watch.themes.R;
import com.umeox.moto.watch.themes.dialog.AlertDialog;

import java.lang.ref.WeakReference;

public class AlertController {

    static final int[] ENABLED_STATE_SET = {android.R.attr.state_enabled};
    static final int[] DISABLED_STATE_SET = {-android.R.attr.state_enabled};
    static final int[] EMPTY_STATE_SET = new int[0];

    private final Context mContext;
    private final DialogInterface mDialogInterface;
    private final Window mWindow;
    private final ButtonBundle mButtonBundlePositive;
    private final ButtonBundle mButtonBundleNegative;
    private final ButtonBundle mButtonBundleNeutral;
    private CharSequence mTitle;
    private CharSequence mMessage;
    private View mView;
    private int mViewLayoutResId;
    private int mViewSpacingLeft;
    private int mViewSpacingTop;
    private int mViewSpacingRight;
    private int mViewSpacingBottom;
    private boolean mViewSpacingSpecified = false;
    private int mIconId = 0;
    private Drawable mIcon;

    private ImageView mIconView;
    private TextView mTitleView;
    private TextView mMessageView;
    private View mCustomTitleView;

    private int mAlertDialogLayout;
    private int mButtonPanelSideLayout;

    private int mButtonPanelLayoutHint = AlertDialog.LAYOUT_HINT_NONE;

    private Handler mHandler;

    private final View.OnClickListener mButtonHandler = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Message m = mButtonBundlePositive.messageForButton(v);
            if (m == null) {
                m = mButtonBundleNegative.messageForButton(v);
            }
            if (m == null) {
                m = mButtonBundleNeutral.messageForButton(v);
            }

            if (m != null) {
                m.sendToTarget();
            }

            // Post a message so we dismiss after the above handlers are executed
            mHandler.obtainMessage(ButtonHandler.MSG_DISMISS_DIALOG, mDialogInterface)
                    .sendToTarget();
        }
    };

    public AlertController(Context context, DialogInterface di, Window window) {
        mContext = context;
        mDialogInterface = di;
        mWindow = window;
        mHandler = new ButtonHandler(di);

        mAlertDialogLayout = R.layout.alert_dialog_uwear;

        mButtonBundlePositive = new ButtonBundle();
        mButtonBundleNegative = new ButtonBundle();
        mButtonBundleNeutral = new ButtonBundle();
    }

    static boolean canTextInput(View v) {
        if (v.onCheckIsTextEditor()) {
            return true;
        }

        if (!(v instanceof ViewGroup)) {
            return false;
        }

        ViewGroup vg = (ViewGroup) v;
        int i = vg.getChildCount();
        while (i > 0) {
            i--;
            v = vg.getChildAt(i);
            if (canTextInput(v)) {
                return true;
            }
        }

        return false;
    }

    public void installContent() {
        /* We use a custom title so never request a window title */
        mWindow.requestFeature(Window.FEATURE_NO_TITLE);
        int contentView = selectContentView();
        mWindow.setContentView(contentView);
        setupView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
            setupDecor();
        }
    }

    private int selectContentView() {
        if (mButtonPanelSideLayout == 0) {
            return mAlertDialogLayout;
        }
        if (mButtonPanelLayoutHint == AlertDialog.LAYOUT_HINT_SIDE) {
            return mButtonPanelSideLayout;
        }
        // TODO: use layout hint side for long messages/lists
        return mAlertDialogLayout;
    }

    public void setTitle(CharSequence title) {
        mTitle = title;
        if (mTitleView != null) {
            mTitleView.setText(title);
        }
    }

    /**
     * @see AlertDialog.Builder#setCustomTitle(View)
     */
    public void setCustomTitle(View customTitleView) {
        mCustomTitleView = customTitleView;
    }

    public void setMessage(CharSequence message) {
        mMessage = message;
        if (mMessageView != null) {
            mMessageView.setText(message);
        }
    }

    /**
     * Set the view resource to display in the dialog.
     */
    public void setView(int layoutResId) {
        mView = null;
        mViewLayoutResId = layoutResId;
        mViewSpacingSpecified = false;
    }

    /**
     * Set the view to display in the dialog.
     */
    public void setView(View view) {
        mView = view;
        mViewLayoutResId = 0;
        mViewSpacingSpecified = false;
    }

    /**
     * Set the view to display in the dialog along with the spacing around that view
     */
    public void setView(View view, int viewSpacingLeft, int viewSpacingTop, int viewSpacingRight,
                        int viewSpacingBottom) {
        mView = view;
        mViewLayoutResId = 0;
        mViewSpacingSpecified = true;
        mViewSpacingLeft = viewSpacingLeft;
        mViewSpacingTop = viewSpacingTop;
        mViewSpacingRight = viewSpacingRight;
        mViewSpacingBottom = viewSpacingBottom;
    }

    /**
     * Sets a hint for the best button panel layout.
     */
    public void setButtonPanelLayoutHint(int layoutHint) {
        mButtonPanelLayoutHint = layoutHint;
    }

    /**
     * Sets a click listener or a message to be sent when the button is clicked.
     * You only need to pass one of {@code listener} or {@code msg}.
     *
     * @param whichButton Which button, can be one of
     *                    {@link DialogInterface#BUTTON_POSITIVE},
     *                    {@link DialogInterface#BUTTON_NEGATIVE}, or
     *                    {@link DialogInterface#BUTTON_NEUTRAL}
     * @param text        The text to display in button.
     * @param listener    The {@link DialogInterface.OnClickListener} to use.
     * @param msg         The {@link Message} to be sent when clicked.
     */
    public void setButton(int whichButton, CharSequence text,
                          DialogInterface.OnClickListener listener, Message msg) {

        if (msg == null && listener != null) {
            msg = mHandler.obtainMessage(whichButton, listener);
        }

        switch (whichButton) {

            case DialogInterface.BUTTON_POSITIVE:
                mButtonBundlePositive.buttonText = text;
                mButtonBundlePositive.buttonMessage = msg;
                break;

            case DialogInterface.BUTTON_NEGATIVE:
                mButtonBundleNegative.buttonText = text;
                mButtonBundleNegative.buttonMessage = msg;
                break;

            case DialogInterface.BUTTON_NEUTRAL:
                mButtonBundleNeutral.buttonText = text;
                mButtonBundleNeutral.buttonMessage = msg;
                break;

            default:
                throw new IllegalArgumentException("Button does not exist");
        }
    }

    /**
     * Specifies the icon to display next to the alert title.
     *
     * @param resId the resource identifier of the drawable to use as the icon,
     *              or 0 for no icon
     */
    public void setIcon(int resId) {
        mIcon = null;
        mIconId = resId;

        if (mIconView != null) {
            if (resId != 0) {
                mIconView.setImageResource(mIconId);
            } else {
                mIconView.setVisibility(View.GONE);
            }
        }
    }

    /**
     * Specifies the icon to display next to the alert title.
     *
     * @param icon the drawable to use as the icon or null for no icon
     */
    public void setIcon(Drawable icon) {
        mIcon = icon;
        mIconId = 0;

        if (mIconView != null) {
            if (icon != null) {
                mIconView.setImageDrawable(icon);
            } else {
                mIconView.setVisibility(View.GONE);
            }
        }
    }

    /**
     * @param attrId the attributeId of the theme-specific drawable
     *               to resolve the resourceId for.
     * @return resId the resourceId of the theme-specific drawable
     */
    public int getIconAttributeResId(int attrId) {
        TypedValue out = new TypedValue();
        mContext.getTheme().resolveAttribute(attrId, out, true);
        return out.resourceId;
    }

    public Button getButton(int whichButton) {
        switch (whichButton) {
            case DialogInterface.BUTTON_POSITIVE:
                return mButtonBundlePositive.textButton;
            case DialogInterface.BUTTON_NEGATIVE:
                return mButtonBundleNegative.textButton;
            case DialogInterface.BUTTON_NEUTRAL:
                return mButtonBundleNeutral.textButton;
            default:
                return null;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT_WATCH)
    private void setupDecor() {
        final View decor = mWindow.getDecorView();
        final View parent = mWindow.findViewById(R.id.parentPanel);
        if (parent != null && decor != null) {
            decor.setOnApplyWindowInsetsListener((view, insets) -> {
                if (insets.isRound()) {
                    // TODO: Get the padding as a function of the window size.
                    int roundOffset = mContext.getResources().getDimensionPixelOffset(
                            R.dimen.alert_dialog_round_padding);
                    parent.setPadding(roundOffset, roundOffset, roundOffset, roundOffset);
                }
                return insets.consumeSystemWindowInsets();
            });
            decor.setFitsSystemWindows(true);
            decor.requestApplyInsets();
        }
    }

    private void setupView() {
        final ViewGroup contentPanel = mWindow.findViewById(R.id.contentPanel);
        setupContent(contentPanel);

        final boolean hasButtons = setupButtons();

        final ViewGroup topPanel = mWindow.findViewById(R.id.topPanel);
        setupTitle(topPanel);

        if (!hasButtons) {
            final View spacer = mWindow.findViewById(R.id.textSpacerNoButtons);
            if (spacer != null) {
                spacer.setVisibility(View.VISIBLE);
            }
        }

        final FrameLayout customPanel = mWindow.findViewById(R.id.customPanel);
        final View customView;
        if (mView != null) {
            customView = mView;
        } else if (mViewLayoutResId != 0) {
            final LayoutInflater inflater = LayoutInflater.from(mContext);
            customView = inflater.inflate(mViewLayoutResId, customPanel, false);
        } else {
            customView = null;
        }

        final boolean hasCustomView = customView != null;
        if (!hasCustomView || !canTextInput(customView)) {
            mWindow.setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
                    WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        }

        if (hasCustomView) {
            final FrameLayout custom = mWindow.findViewById(R.id.custom);
            custom.addView(customView, new LayoutParams(MATCH_PARENT, MATCH_PARENT));

            if (mViewSpacingSpecified) {
                custom.setPadding(
                        mViewSpacingLeft, mViewSpacingTop, mViewSpacingRight, mViewSpacingBottom);
            }
            customPanel.setVisibility(View.VISIBLE);
        } else {
            customPanel.setVisibility(View.GONE);
        }
    }

    private boolean setupTitle(ViewGroup topPanel) {
        boolean hasTitle = true;

        if (mCustomTitleView != null) {
            // Add the custom title view directly to the topPanel layout
            LayoutParams lp = new LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

            topPanel.addView(mCustomTitleView, 0, lp);

            // Hide the title template
            View titleTemplate = mWindow.findViewById(R.id.title_template);
            titleTemplate.setVisibility(View.GONE);
        } else {
            final boolean hasTextTitle = !TextUtils.isEmpty(mTitle);
            final boolean hasIconTitle = mIconId != 0 || mIcon != null;
            if (hasTextTitle || hasIconTitle) {
                mTitleView = (TextView) mWindow.findViewById(android.R.id.title);
                mIconView = (ImageView) mWindow.findViewById(android.R.id.icon);

                if (hasTextTitle) {
                    // Display the title if a title is supplied, else hide it.
                    mTitleView.setText(mTitle);
                } else {
                    mTitleView.setVisibility(View.GONE);
                }

                // Do this last so that if the user has supplied any icons we
                // use them instead of the default ones. If the user has
                // specified 0 then make it disappear.
                if (mIconId != 0) {
                    mIconView.setImageResource(mIconId);
                } else if (mIcon != null) {
                    mIconView.setImageDrawable(mIcon);
                } else {
                    mIconView.setVisibility(View.GONE);
                }
            } else {
                // Hide the title template
                final View titleTemplate = mWindow.findViewById(R.id.title_template);
                titleTemplate.setVisibility(View.GONE);
                hasTitle = false;
            }
        }
        return hasTitle;
    }

    @SuppressLint("NewApi")
    private void setupContent(ViewGroup contentPanel) {
        // Special case for users that only want to display a String
        mMessageView = (TextView) mWindow.findViewById(R.id.message);
        if (mMessageView == null) {
            return;
        }

        if (mMessage != null) {
            mMessageView.setText(mMessage);
        } else {
            mMessageView.setVisibility(View.GONE);
            contentPanel.setVisibility(View.GONE);
        }

        // Set up scroll indicators (if present).
        final View indicatorUp = mWindow.findViewById(R.id.scrollIndicatorUp);
        final View indicatorDown = mWindow.findViewById(R.id.scrollIndicatorDown);
        if (indicatorUp != null || indicatorDown != null) {
            if (mMessage == null) {
                // We don't have any content to scroll, remove the indicators.
                if (indicatorUp != null) {
                    contentPanel.removeView(indicatorUp);
                }
                if (indicatorDown != null) {
                    contentPanel.removeView(indicatorDown);
                }
            }
        }
    }

    private boolean setupButtons() {
        setupButtonBundles();
        int textButtonCount = setupTextButtons();
        boolean hasButtons = textButtonCount > 0;

        final View textButtonPanel = mWindow.findViewById(R.id.textButtonPanel);
        if (hasButtons) {
            textButtonPanel.setVisibility(View.VISIBLE);
        } else {
            textButtonPanel.setVisibility(View.GONE);
        }
        resetButtons(textButtonCount);
        return hasButtons;
    }

    private void setupButtonBundles() {
        mButtonBundlePositive.setup(mWindow, R.id.textButton1, R.id.space1);
        mButtonBundleNegative.setup(mWindow, R.id.textButton2, R.id.space2);
        mButtonBundleNeutral.setup(mWindow, R.id.textButton3, R.id.space3);
    }

    private int setupTextButtons() {
        int BIT_BUTTON_POSITIVE = 1;
        int BIT_BUTTON_NEGATIVE = 2;
        int BIT_BUTTON_NEUTRAL = 4;
        int whichButtons = 0;
        if (mButtonBundlePositive.setupTextButton(mButtonHandler)) {
            whichButtons = whichButtons | BIT_BUTTON_POSITIVE;
        }
        if (mButtonBundleNegative.setupTextButton(mButtonHandler)) {
            whichButtons = whichButtons | BIT_BUTTON_NEGATIVE;
        }
        if (mButtonBundleNeutral.setupTextButton(mButtonHandler)) {
            whichButtons = whichButtons | BIT_BUTTON_NEUTRAL;
        }

        return Integer.bitCount(whichButtons);
    }

    private void resetButtons(int buttonCount) {
        int buttonFullWidthUnit = mContext.getResources()
                .getDimensionPixelOffset(R.dimen.u_primary_button_full_width);
        int buttonHalfWidthUnit = mContext.getResources()
                .getDimensionPixelOffset(R.dimen.u_primary_button_half_width);
        int buttonPaddingUnit = mContext.getResources()
                .getDimensionPixelOffset(R.dimen.u_primary_button_padding);
        int buttonWidth;
        if (buttonCount == 3) {
            buttonWidth = (buttonFullWidthUnit - buttonPaddingUnit * 2) / 3;
        } else if (buttonCount == 2) {
            buttonWidth = buttonHalfWidthUnit;
        } else {
            buttonWidth = buttonFullWidthUnit;
        }

        LinearLayout.LayoutParams lp;
        lp = getLinearLayoutParams(mButtonBundlePositive.textButton);
        if (lp != null) {
            lp.width = buttonWidth;
            mButtonBundlePositive.textButton.setLayoutParams(lp);
        }
        lp = getLinearLayoutParams(mButtonBundleNegative.textButton);
        if (lp != null) {
            lp.width = buttonWidth;
            mButtonBundleNegative.textButton.setLayoutParams(lp);
        }
        lp = getLinearLayoutParams(mButtonBundleNeutral.textButton);
        if (lp != null) {
            lp.width = buttonWidth;
            mButtonBundleNeutral.textButton.setLayoutParams(lp);
        }
    }

    private LinearLayout.LayoutParams getLinearLayoutParams(View view) {
        return view.getLayoutParams() instanceof LinearLayout.LayoutParams ?
                (LinearLayout.LayoutParams) view.getLayoutParams() : null;
    }

    private static final class ButtonHandler extends Handler {
        // Button clicks have Message.what as the BUTTON{1,2,3} constant
        private static final int MSG_DISMISS_DIALOG = 1;

        private WeakReference<DialogInterface> mDialog;

        public ButtonHandler(DialogInterface dialog) {
            mDialog = new WeakReference<DialogInterface>(dialog);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DialogInterface.BUTTON_POSITIVE:
                case DialogInterface.BUTTON_NEGATIVE:
                case DialogInterface.BUTTON_NEUTRAL:
                    ((DialogInterface.OnClickListener) msg.obj).onClick(mDialog.get(), msg.what);
                    break;
                case MSG_DISMISS_DIALOG:
                    ((DialogInterface) msg.obj).dismiss();
            }
        }
    }

    public static class AlertParams {
        public final Context mContext;
        public final LayoutInflater mInflater;

        public int mIconId = 0;
        public Drawable mIcon;
        public int mIconAttrId = 0;
        public CharSequence mTitle;
        public View mCustomTitleView;
        public CharSequence mMessage;
        public CharSequence mPositiveButtonText;
        public DialogInterface.OnClickListener mPositiveButtonListener;
        public CharSequence mNegativeButtonText;
        public DialogInterface.OnClickListener mNegativeButtonListener;
        public CharSequence mNeutralButtonText;
        public DialogInterface.OnClickListener mNeutralButtonListener;
        public boolean mCancelable;
        public DialogInterface.OnCancelListener mOnCancelListener;
        public DialogInterface.OnDismissListener mOnDismissListener;
        public DialogInterface.OnKeyListener mOnKeyListener;
        public int mViewLayoutResId;
        public View mView;
        public int mViewSpacingLeft;
        public int mViewSpacingTop;
        public int mViewSpacingRight;
        public int mViewSpacingBottom;
        public boolean mViewSpacingSpecified = false;

        public AlertParams(Context context) {
            mContext = context;
            mCancelable = true;
            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        public void apply(AlertController dialog) {
            if (mCustomTitleView != null) {
                dialog.setCustomTitle(mCustomTitleView);
            } else {
                if (mTitle != null) {
                    dialog.setTitle(mTitle);
                }
                if (mIcon != null) {
                    dialog.setIcon(mIcon);
                }
                if (mIconId != 0) {
                    dialog.setIcon(mIconId);
                }
                if (mIconAttrId != 0) {
                    dialog.setIcon(dialog.getIconAttributeResId(mIconAttrId));
                }
            }
            if (mMessage != null) {
                dialog.setMessage(mMessage);
            }
            if (mPositiveButtonText != null) {
                dialog.setButton(DialogInterface.BUTTON_POSITIVE, mPositiveButtonText, mPositiveButtonListener, null);
            }
            if (mNegativeButtonText != null) {
                dialog.setButton(DialogInterface.BUTTON_NEGATIVE, mNegativeButtonText, mNegativeButtonListener, null);
            }
            if (mNeutralButtonText != null) {
                dialog.setButton(DialogInterface.BUTTON_NEUTRAL, mNeutralButtonText, mNeutralButtonListener, null);
            }
            if (mView != null) {
                if (mViewSpacingSpecified) {
                    dialog.setView(mView, mViewSpacingLeft, mViewSpacingTop, mViewSpacingRight,
                            mViewSpacingBottom);
                } else {
                    dialog.setView(mView);
                }
            } else if (mViewLayoutResId != 0) {
                dialog.setView(mViewLayoutResId);
            }

        }
    }

    private static class ButtonBundle {
        private Button textButton;
        private Space textSpace;
        private CharSequence buttonText;
        private Message buttonMessage;

        public void setup(Window window,
                          @IdRes int textButtonId, @IdRes int textSpaceId) {
            textButton = window.findViewById(textButtonId);
            textSpace = window.findViewById(textSpaceId);
        }

        public Message messageForButton(View v) {
            if (v == textButton && buttonMessage != null) {
                return Message.obtain(buttonMessage);
            }
            return null;
        }

        public boolean setupTextButton(@Nullable View.OnClickListener l) {
            textButton.setOnClickListener(l);

            if (TextUtils.isEmpty(buttonText)) {
                textButton.setVisibility(View.GONE);
                textSpace.setVisibility(View.GONE);
                return false;
            } else {
                textButton.setText(buttonText);
                textButton.setVisibility(View.VISIBLE);
                textSpace.setVisibility(View.INVISIBLE);
                return true;
            }
        }

        public boolean isVisibility() {
            return !TextUtils.isEmpty(buttonText);
        }
    }
}
